<?php
/**
 * Created by PhpStorm.
 * User: 技术员专用
 * Date: 2019/3/19
 * Time: 11:09
 */

namespace app\common\lib\redis;

use app\common\lib\Redis;
use think\Exception;

class Predis
{
    const HOST='127.0.0.1';
    const PORT=6379;
    const timeOut=5;
    public $redis = "";
    /**
     * 定义单例模式的变量
     * @var null
     */
    private static $_instance = null;

    public static function getInstance() {
        if(empty(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    private function __construct() {
        $this->redis = new \Redis();
        $result = $this->redis->connect(self::HOST, self::PORT, self::timeOut);
        if($result === false) {
            throw new \Exception('redis connect error');
        }
    }

    /**
     * set
     * @param $key
     * @param $value
     * @param int $time
     * @return bool|string
     */
    public function set($key, $value, $time = 0 ) {
        if(!$key) {
            return '';
        }
        if(is_array($value)) {
            $value = json_encode($value);
        }
        if(!$time) {
            return $this->redis->set($key, $value);
        }

        return $this->redis->setex($key, $time, $value);
    }

    /**
     * get
     * @param $key
     * @return bool|string
     */
    public function get($key) {
        if(!$key) {
            return '';
        }

        return $this->redis->get($key);
    }

    public function sadd($key,$value){
        return $this->redis->sAdd($key,$value);
    }
    public function srem($key,$value){
        return $this->redis->sRem($key,$value);
    }
    public function smember($key){
        return $this->redis->sMembers($key);
    }
    public function __call($name, $arguments)
    {
        $arguments=implode(',',$arguments);
        $this->redis->$name($arguments);
    }
}